package zcj.stu.service;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import zcj.stu.Entity.Goods;
import zcj.stu.Entity.Order;
import zcj.stu.dao.GoodsDao;
import zcj.stu.utils.Result;
import zcj.stu.vo.ShopVo;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class GoodsService {
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private CategoryService categoryService;
    public Result getAllShops() {
        List<Goods>allG=all();
        if(allG==null||allG.size()<1)return Result.ok();
        List<ShopVo>shopVos=new ArrayList<>();
        HashMap<String, ShopVo> map = new HashMap<>();
        for (Goods goods : allG) {
            Order.Goods rGoods = new Order.Goods();
            rGoods.set_id(goods.get_id());
            rGoods.setGoods_count(goods.getNum());
            rGoods.setGoods_desc(goods.getDesc());
            rGoods.setGoods_name(goods.getName());
            rGoods.setGoods_price(goods.getPrice());
            rGoods.setImg(goods.getImgs());

            String category = goods.getCategory();
            ShopVo shopVo = map.get(category);
            if(shopVo==null){
                shopVo=new ShopVo();
                shopVo.setCategory(category);
                shopVo.setGoods(new ArrayList<>());
                map.put(category,shopVo);
                shopVos  .add(shopVo);
            }
            shopVo.getGoods().add(rGoods);
        }
        return Result.ok(shopVos);
    }
    public boolean add(Goods goods) {
         return goodsDao.add(goods)!=null;
    }

    public boolean edit(Goods goods) {
        Query query = Query.query(Criteria.where("_id").is(goods.get_id()));
        Update update = new Update();
        update.set("name",goods.getName());
        update.set("price",goods.getPrice());
        update.set("num",goods.getNum());
        update.set("isSale",goods.getIsSale());
        update.set("desc",goods.getDesc());
        update.set("imgs",goods.getImgs());
        update.set("category",goods.getCategory());
        return goodsDao.edit(query,update).getModifiedCount()>0;
    }

    public boolean del(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        return goodsDao.del(query).getDeletedCount()>0;
    }

    public List<Goods> all() {
        return goodsDao.all(Query.query(Criteria.where("isSale").is("true")));
    }
}
